package com.bkhc.product.repository;

import com.bkhc.common.enu.PartnershipEnum;
import com.bkhc.product.entity.Brand;
import com.bkhc.product.entity.Partner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface PartnerRepository extends JpaRepository<Partner,String>, JpaSpecificationExecutor<Partner> {

    default Page<Partner> findAll(Partner partner, Pageable pageable){
        return findAll(new Specification<Partner>() {
            @Override
            public Predicate toPredicate(Root<Partner> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(partner.getPartnerCode())){
                    predicate.add(criteriaBuilder.equal(root.get("partnerCode").as(String.class), partner.getPartnerCode()));
                }
                if(!StringUtils.isEmpty(partner.getPartnerName())){
                    predicate.add(criteriaBuilder.like(root.get("partnerName").as(String.class),"%"+ partner.getPartnerName()+"%"));
                }
                if(partner.getPartnership()!=null){
                    predicate.add(criteriaBuilder.equal(root.get("partnership").as(String.class), partner.getPartnership().getCode()));
                }
                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);
    }

    Partner findByPartnerName(String partnerName);

    Partner findByPartnerCode(String partnerCode);

    void deleteByPartnerCode(String partnerCode);
}
